# 首先获取当前目录及其子目录下的所有 .c, .cpp, 和 .h 文件
file(GLOB_RECURSE SOURCES "*.c" "*.cpp")
file(GLOB_RECURSE HEADERS "*.h")

# 将找到的源文件和头文件合并成一个列表
list(APPEND ALL_FILES ${SOURCES} ${HEADERS})

# 创建一个空列表用于存放所有目录
set(INCLUDE_DIRS "")

# 遍历所有文件，提取目录并去重
foreach(FILE_PATH IN LISTS ALL_FILES)
    get_filename_component(DIR_PATH ${FILE_PATH} DIRECTORY)
    if(NOT ${DIR_PATH} IN_LIST INCLUDE_DIRS)
        list(APPEND INCLUDE_DIRS ${DIR_PATH})
    endif()
endforeach()

# 设置依赖项列表
set(requires "nvs_flash" "esp_psram" "esp_timer" "usb")

# 注册组件
idf_component_register(
    SRCS ${SOURCES}
    INCLUDE_DIRS ${INCLUDE_DIRS}
    REQUIRES "${requires}"
)

# 获取当前目录
set(CURRENT_DIR ${CMAKE_CURRENT_SOURCE_DIR})

# 获取tusb_lib目标
idf_component_get_property(tusb_lib espressif__tinyusb COMPONENT_LIB)
if(NOT tusb_lib)
    message(FATAL_ERROR "Target 'tusb_lib' not found. Please ensure that the component 'espressif__tinyusb' is correctly defined.")
endif()

# 添加tusb目录下的头文件路径
target_include_directories(${tusb_lib} PUBLIC "${CURRENT_DIR}/bsp/tusb")

# 添加tusb目录下的源文件
target_sources(${tusb_lib} PUBLIC "${CURRENT_DIR}/bsp/tusb/usb_descriptors.c")

# 清理临时变量
unset(SOURCES)
unset(HEADERS)
unset(ALL_FILES)
unset(INCLUDE_DIRS)